import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import '../models/server_config.dart';

/// V2Ray/Xray 核心服务
/// 通过直接调用 V2Ray/Xray 可执行文件实现真实代理功能
class V2RayCoreService {
  Process? _coreProcess;
  bool _isRunning = false;
  String? _configPath;
  
  /// 检查是否正在运行
  bool get isRunning => _isRunning;
  
  /// 启动 V2Ray/Xray 核心
  Future<bool> start(ServerConfig server) async {
    print('');
    print('═══════════════════════════════════════');
    print('   开始启动 V2Ray/Xray 核心');
    print('═══════════════════════════════════════');
    
    if (_isRunning) {
      print('⚠️ V2Ray 核心已在运行中，跳过启动');
      return true;
    }
    
    try {
      print('');
      print('步骤 1/6: 生成配置文件');
      print('─────────────────────────────────────');
      
      // 1. 生成配置文件
      final config = _generateV2RayConfig(server);
      final configFile = await _writeConfigFile(config);
      _configPath = configFile.path;
      
      print('✅ 配置文件已生成: $_configPath');
      print('🔧 配置内容预览:');
      print(config.substring(0, config.length > 500 ? 500 : config.length));
      if (config.length > 500) print('...(配置文件较长，已截断)');
      
      print('');
      print('步骤 2/6: 查找可执行文件');
      print('─────────────────────────────────────');
      
      // 2. 查找 V2Ray/Xray 可执行文件
      final executable = await _findV2RayExecutable();
      if (executable == null) {
        print('');
        print('❌ 未找到 V2Ray/Xray 可执行文件');
        print('');
        print('提示: 请下载 V2Ray 或 Xray 核心并放置到以下位置之一:');
        print('  1. 项目根目录/v2ray-core/');
        print('  2. 项目根目录/xray-core/');
        print('  3. 系统 PATH 环境变量中');
        print('\n下载地址:');
        print('  V2Ray: https://github.com/v2fly/v2ray-core/releases');
        print('  Xray:  https://github.com/XTLS/Xray-core/releases');
        return false;
      }
      
      print('🔍 找到可执行文件: $executable');
      
      // 3. 启动核心进程（使用 normal 模式以便监听输出）
      print('🚀 正在启动 V2Ray/Xray 核心...');
      _coreProcess = await Process.start(
        executable,
        ['run', '-config', configFile.path],
        mode: ProcessStartMode.normal,  // 改为 normal 模式
      );
      
      _isRunning = true;
      print('✅ 进程已启动，PID: ${_coreProcess!.pid}');
      
      // 4. 监听输出（异步，不阻塞）
      _coreProcess!.stdout.transform(utf8.decoder).listen(
        (data) {
          print('📡 V2Ray输出: ${data.trim()}');
        },
        onError: (error) {
          print('⚠️ V2Ray stdout错误: $error');
        },
      );
      
      _coreProcess!.stderr.transform(utf8.decoder).listen(
        (data) {
          print('⚠️ V2Ray错误: ${data.trim()}');
        },
        onError: (error) {
          print('⚠️ V2Ray stderr错误: $error');
        },
      );
      
      // 监听进程退出
      _coreProcess!.exitCode.then((exitCode) {
        print('');
        print('⚠️ V2Ray 进程已退出，退出码: $exitCode');
        _isRunning = false;
      });
      
      print('');
      print('步骤 5/6: 等待核心初始化');
      print('─────────────────────────────────────');
      
      // 5. 等待启动完成（给核心一些时间初始化）
      print('⏳ 等待 3 秒，让核心完成初始化...');
      await Future.delayed(const Duration(seconds: 3));
      print('✅ 初始化等待完成');
      
      print('');
      print('步骤 6/6: 设置系统代理');
      print('─────────────────────────────────────');
      
      // 6. 设置系统代理
      await _setSystemProxy('127.0.0.1:10808');
      
      print('');
      print('═══════════════════════════════════════');
      print('   🎉 V2Ray 核心启动成功！');
      print('═══════════════════════════════════════');
      print('📡 SOCKS5 代理: 127.0.0.1:10808');
      print('📡 HTTP 代理:   127.0.0.1:10809');
      print('🌐 系统代理已自动设置');
      print('✨ 现在可以访问 YouTube 等网站了！');
      print('═══════════════════════════════════════');
      print('');
      
      return true;
    } catch (e, stackTrace) {
      print('');
      print('═══════════════════════════════════════');
      print('   ❌ 启动失败');
      print('═══════════════════════════════════════');
      print('错误: $e');
      print('');
      print('堆栈跟踪:');
      print(stackTrace);
      print('═══════════════════════════════════════');
      print('');
      _isRunning = false;
      return false;
    }
  }
  
  /// 停止 V2Ray/Xray 核心
  Future<void> stop() async {
    print('');
    print('═══════════════════════════════════════');
    print('   停止 V2Ray/Xray 核心');
    print('═══════════════════════════════════════');
    
    if (!_isRunning) {
      print('ℹ️ 核心未运行，无需停止');
      return;
    }
    
    try {
      print('');
      print('步骤 1/3: 清除系统代理');
      print('─────────────────────────────────────');
      
      // 1. 清除系统代理
      await _clearSystemProxy();
      
      print('');
      print('步骤 2/3: 停止核心进程');
      print('─────────────────────────────────────');
      
      // 2. 停止核心进程
      if (_coreProcess != null) {
        print('🔪 终止进程 PID: ${_coreProcess!.pid}');
        _coreProcess!.kill();
        await _coreProcess!.exitCode.timeout(
          const Duration(seconds: 5),
          onTimeout: () {
            print('⚠️ 等待进程退出超时');
            return -1;
          },
        );
        _coreProcess = null;
        print('✅ 进程已停止');
      }
      
      print('');
      print('步骤 3/3: 清理配置文件');
      print('─────────────────────────────────────');
      
      // 3. 清理配置文件
      if (_configPath != null) {
        final file = File(_configPath!);
        if (await file.exists()) {
          await file.delete();
          print('✅ 配置文件已删除: $_configPath');
        }
        _configPath = null;
      }
      
      _isRunning = false;
      
      print('');
      print('═══════════════════════════════════════');
      print('   ✅ 已成功停止');
      print('═══════════════════════════════════════');
      print('');
    } catch (e) {
      print('');
      print('❌ 停止失败: $e');
      print('');
      _isRunning = false;
    }
  }
  
  /// 查找 V2Ray/Xray 可执行文件
  Future<String?> _findV2RayExecutable() async {
    // 1. 首先检查应用数据目录（从 assets 提取的位置）
    try {
      final appDir = await getApplicationSupportDirectory();
      String exeName = 'xray';
      
      if (Platform.isWindows) {
        exeName = 'xray.exe';
      } else if (Platform.isMacOS) {
        exeName = 'xray';
      } else if (Platform.isLinux) {
        exeName = 'xray';
      } else if (Platform.isAndroid) {
        exeName = 'libxray.so'; // Android 使用 .so 库
      } else if (Platform.isIOS) {
        exeName = 'xray'; // iOS 使用静态库或框架
      }
      
      final extractedXray = File('${appDir.path}/xray-core/$exeName');
      
      if (await extractedXray.exists()) {
        print('✅ 找到已提取的 $exeName: ${extractedXray.path}');
        return extractedXray.absolute.path;
      } else {
        print('ℹ️ 应用数据目录中未找到 $exeName，尝试从 assets 提取...');
        final extracted = await _extractXrayFromAssets();
        if (extracted != null) {
          return extracted;
        }
      }
    } catch (e) {
      print('⚠️ 检查应用数据目录失败: $e');
    }
    
    // 2. 检查项目根目录（开发环境）
    final possiblePaths = _getPlatformSpecificPaths();
    
    for (final path in possiblePaths) {
      final file = File(path);
      if (await file.exists()) {
        print('✅ 在开发目录找到: ${file.absolute.path}');
        return file.absolute.path;
      }
    }
    
    // 3. 检查系统 PATH
    final systemPath = await _findInSystemPath();
    if (systemPath != null) {
      return systemPath;
    }
    
    return null;
  }

  /// 获取平台特定的可执行文件路径列表
  List<String> _getPlatformSpecificPaths() {
    if (Platform.isWindows) {
      return [
        'v2ray-core/v2ray.exe',
        'xray-core/xray.exe',
        'v2ray.exe',
        'xray.exe',
      ];
    } else if (Platform.isMacOS) {
      return [
        'v2ray-core/v2ray',
        'xray-core/xray',
        'v2ray',
        'xray',
        '/usr/local/bin/xray',
        '/usr/local/bin/v2ray',
        '/opt/homebrew/bin/xray',
        '/opt/homebrew/bin/v2ray',
      ];
    } else if (Platform.isLinux) {
      return [
        'v2ray-core/v2ray',
        'xray-core/xray',
        'v2ray',
        'xray',
        '/usr/bin/xray',
        '/usr/bin/v2ray',
        '/usr/local/bin/xray',
        '/usr/local/bin/v2ray',
      ];
    } else if (Platform.isAndroid) {
      return [
        'xray-core/libxray.so',
        'libxray.so',
      ];
    } else if (Platform.isIOS) {
      return [
        'xray-core/xray',
        'xray',
      ];
    } else {
      return [];
    }
  }

  /// 在系统 PATH 中查找可执行文件
  Future<String?> _findInSystemPath() async {
    if (Platform.isWindows) {
      // Windows 使用 where 命令
      for (final name in ['xray', 'v2ray']) {
        try {
          final result = await Process.run('where', [name]);
          if (result.exitCode == 0) {
            final path = (result.stdout as String).trim().split('\n').first;
            print('✅ 在系统 PATH 找到 $name: $path');
            return path;
          }
        } catch (e) {
          // 继续尝试下一个
        }
      }
    } else {
      // Unix-like 系统使用 which 命令
      for (final name in ['xray', 'v2ray']) {
        try {
          final result = await Process.run('which', [name]);
          if (result.exitCode == 0) {
            final path = (result.stdout as String).trim();
            print('✅ 在系统 PATH 找到 $name: $path');
            return path;
          }
        } catch (e) {
          // 继续尝试下一个
        }
      }
    }
    
    return null;
  }
  
  /// 从 assets 提取 Xray 可执行文件
  Future<String?> _extractXrayFromAssets() async {
    try {
      String assetPath = 'xray-core/xray';
      String exeName = 'xray';
      
      // 根据平台确定文件名
      if (Platform.isWindows) {
        assetPath = 'xray-core/xray.exe';
        exeName = 'xray.exe';
      } else if (Platform.isMacOS) {
        assetPath = 'xray-core/xray-macos';
        exeName = 'xray';
      } else if (Platform.isLinux) {
        assetPath = 'xray-core/xray-linux';
        exeName = 'xray';
      } else if (Platform.isAndroid) {
        assetPath = 'xray-core/libxray.so';
        exeName = 'libxray.so';
      } else if (Platform.isIOS) {
        assetPath = 'xray-core/xray-ios';
        exeName = 'xray';
      }
      
      print('📦 正在从 assets 提取 $exeName...');
      print('📍 Asset 路径: $assetPath');
      
      // 读取 asset
      final byteData = await rootBundle.load(assetPath);
      
      // 获取应用数据目录
      final appDir = await getApplicationSupportDirectory();
      final xrayCoreDir = Directory('${appDir.path}/xray-core');
      
      // 创建目录
      if (!await xrayCoreDir.exists()) {
        await xrayCoreDir.create(recursive: true);
      }
      
      // 写入文件
      final xrayFile = File('${xrayCoreDir.path}/$exeName');
      await xrayFile.writeAsBytes(byteData.buffer.asUint8List());
      
      // 设置可执行权限（Unix-like 系统）
      if (!Platform.isWindows && !Platform.isAndroid) {
        await Process.run('chmod', ['+x', xrayFile.path]);
        print('✅ 已设置可执行权限');
      }
      
      print('✅ $exeName 已提取到: ${xrayFile.path}');
      return xrayFile.absolute.path;
    } catch (e) {
      print('⚠️ 从 assets 提取失败: $e');
      print('💡 这是正常的，如果您在开发环境中，请确保相应的可执行文件存在');
      
      if (Platform.isWindows) {
        print('   Windows: xray-core/xray.exe');
      } else if (Platform.isMacOS) {
        print('   macOS: xray-core/xray-macos');
      } else if (Platform.isLinux) {
        print('   Linux: xray-core/xray-linux');
      } else if (Platform.isAndroid) {
        print('   Android: xray-core/libxray.so');
      } else if (Platform.isIOS) {
        print('   iOS: xray-core/xray-ios');
      }
      
      return null;
    }
  }
  
  /// 写入配置文件
  Future<File> _writeConfigFile(String config) async {
    final tempDir = await getTemporaryDirectory();
    final configFile = File('${tempDir.path}/v2ray_config_${DateTime.now().millisecondsSinceEpoch}.json');
    await configFile.writeAsString(config);
    return configFile;
  }
  
  /// 生成 V2Ray 配置
  String _generateV2RayConfig(ServerConfig server) {
    final config = {
      'log': {
        'loglevel': 'warning',
      },
      'inbounds': [
        {
          'port': 10808,
          'protocol': 'socks',
          'settings': {
            'auth': 'noauth',
            'udp': true,
          },
          'sniffing': {
            'enabled': true,
            'destOverride': ['http', 'tls'],
          },
        },
        {
          'port': 10809,
          'protocol': 'http',
          'settings': {
            'timeout': 0,
          },
        },
      ],
      'outbounds': [
        _generateOutbound(server),
        {
          'protocol': 'freedom',
          'tag': 'direct',
        },
      ],
    };
    
    return const JsonEncoder.withIndent('  ').convert(config);
  }
  
  /// 生成出站配置
  Map<String, dynamic> _generateOutbound(ServerConfig server) {
    final outbound = <String, dynamic>{
      'protocol': server.protocol.toLowerCase(),
      'settings': <String, dynamic>{},
      'streamSettings': <String, dynamic>{
        'network': server.network,
      },
    };
    
    // 根据协议类型生成不同的配置
    switch (server.protocol.toLowerCase()) {
      case 'vmess':
        final vnextList = <Map<String, dynamic>>[];
        final usersList = <Map<String, dynamic>>[];
        
        final user = <String, dynamic>{};
        user['id'] = server.userId;
        user['alterId'] = server.alterId;
        user['security'] = server.security;
        usersList.add(user);
        
        final vnextItem = <String, dynamic>{};
        vnextItem['address'] = server.address;
        vnextItem['port'] = server.port;
        vnextItem['users'] = usersList;
        vnextList.add(vnextItem);
        
        final settings = <String, dynamic>{};
        settings['vnext'] = vnextList;
        outbound['settings'] = settings;
        break;
        
      case 'vless':
        final vnextList = <Map<String, dynamic>>[];
        final usersList = <Map<String, dynamic>>[];
        
        final user = <String, dynamic>{};
        user['id'] = server.userId;
        user['encryption'] = 'none';
        usersList.add(user);
        
        final vnextItem = <String, dynamic>{};
        vnextItem['address'] = server.address;
        vnextItem['port'] = server.port;
        vnextItem['users'] = usersList;
        vnextList.add(vnextItem);
        
        final settings = <String, dynamic>{};
        settings['vnext'] = vnextList;
        outbound['settings'] = settings;
        break;
        
      case 'trojan':
        final serversList = <Map<String, dynamic>>[];
        
        final serverItem = <String, dynamic>{};
        serverItem['address'] = server.address;
        serverItem['port'] = server.port;
        serverItem['password'] = server.userId;
        serversList.add(serverItem);
        
        final settings = <String, dynamic>{};
        settings['servers'] = serversList;
        outbound['settings'] = settings;
        break;
        
      case 'shadowsocks':
        final serversList = <Map<String, dynamic>>[];
        
        final serverItem = <String, dynamic>{};
        serverItem['address'] = server.address;
        serverItem['port'] = server.port;
        serverItem['method'] = server.security;
        serverItem['password'] = server.userId;
        serversList.add(serverItem);
        
        final settings = <String, dynamic>{};
        settings['servers'] = serversList;
        outbound['settings'] = settings;
        break;
    }
    
    // TLS 设置
    if (server.tls != null && server.tls!.isNotEmpty && server.tls != 'none') {
      outbound['streamSettings']['security'] = server.tls;
      
      final tlsSettings = <String, dynamic>{
        'allowInsecure': false,
      };
      
      // 只在 SNI 存在时添加，否则使用地址
      if (server.sni != null && server.sni!.isNotEmpty) {
        tlsSettings['serverName'] = server.sni!;
      } else {
        tlsSettings['serverName'] = server.address;
      }
      
      outbound['streamSettings']['tlsSettings'] = tlsSettings;
    }
    
    // 传输层设置
    switch (server.network) {
      case 'ws':
        final wsSettings = <String, dynamic>{};
        
        // 设置 path
        if (server.path != null && server.path!.isNotEmpty) {
          wsSettings['path'] = server.path!;
        } else {
          wsSettings['path'] = '/';
        }
        
        // 只在 host 不为空时添加 headers
        if (server.host != null && server.host!.isNotEmpty) {
          final headers = <String, String>{};
          headers['Host'] = server.host!;
          wsSettings['headers'] = headers;
        }
        
        outbound['streamSettings']['wsSettings'] = wsSettings;
        break;
        
      case 'tcp':
        // TCP settings (header type not in current ServerConfig model)
        break;
        
      case 'grpc':
        final grpcSettings = <String, dynamic>{};
        if (server.path != null && server.path!.isNotEmpty) {
          grpcSettings['serviceName'] = server.path!;
        } else {
          grpcSettings['serviceName'] = '';
        }
        outbound['streamSettings']['grpcSettings'] = grpcSettings;
        break;
    }
    
    return outbound;
  }
  
  /// 设置系统代理（跨平台）
  Future<void> _setSystemProxy(String proxy) async {
    try {
      if (Platform.isWindows) {
        await _setWindowsProxy(proxy);
      } else if (Platform.isMacOS) {
        await _setMacOSProxy(proxy);
      } else if (Platform.isLinux) {
        await _setLinuxProxy(proxy);
      } else if (Platform.isAndroid) {
        print('ℹ️ Android 系统代理需要在系统设置中手动配置');
        print('💡 或者应用将通过 VPN Service 自动路由所有流量');
      } else if (Platform.isIOS) {
        print('ℹ️ iOS 系统代理需要在系统设置中手动配置');
        print('💡 或者应用将通过 Network Extension 自动路由所有流量');
      } else {
        print('⚠️ 未知平台，无法设置系统代理');
      }
    } catch (e) {
      print('⚠️ 设置系统代理失败: $e');
      print('💡 您可以手动在系统设置中配置代理: $proxy');
    }
  }

  /// 设置 Windows 系统代理
  Future<void> _setWindowsProxy(String proxy) async {
    try {
      // 启用代理
      await Process.run('reg', [
        'add',
        'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
        '/v',
        'ProxyEnable',
        '/t',
        'REG_DWORD',
        '/d',
        '1',
        '/f',
      ]);
      
      // 设置代理地址
      await Process.run('reg', [
        'add',
        'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
        '/v',
        'ProxyServer',
        '/d',
        proxy,
        '/f',
      ]);
      
      print('✅ Windows 系统代理已设置: $proxy');
      print('🌐 现在您可以直接在浏览器中访问 YouTube 等网站了！');
    } catch (e) {
      print('⚠️ 设置 Windows 代理失败: $e');
      rethrow;
    }
  }

  /// 设置 macOS 系统代理
  Future<void> _setMacOSProxy(String proxy) async {
    try {
      final parts = proxy.split(':');
      final host = parts[0];
      final port = parts.length > 1 ? parts[1] : '10808';

      // 获取所有网络服务
      final result = await Process.run('networksetup', ['-listallnetworkservices']);
      if (result.exitCode != 0) {
        throw Exception('无法获取网络服务列表');
      }

      final services = (result.stdout as String)
          .split('\n')
          .where((line) => line.isNotEmpty && !line.startsWith('*'))
          .toList();

      for (final service in services) {
        if (service.trim().isEmpty) continue;

        // 设置 SOCKS 代理
        await Process.run('networksetup', [
          '-setsocksfirewallproxy',
          service.trim(),
          host,
          port,
        ]);

        // 启用 SOCKS 代理
        await Process.run('networksetup', [
          '-setsocksfirewallproxystate',
          service.trim(),
          'on',
        ]);

        print('✅ 已为 $service 设置 SOCKS 代理');
      }

      print('✅ macOS 系统代理已设置: $proxy');
      print('🌐 现在您可以直接在浏览器中访问 YouTube 等网站了！');
    } catch (e) {
      print('⚠️ 设置 macOS 代理失败: $e');
      print('💡 您可能需要手动在"系统偏好设置 > 网络 > 高级 > 代理"中配置');
      rethrow;
    }
  }

  /// 设置 Linux 系统代理
  Future<void> _setLinuxProxy(String proxy) async {
    try {
      final parts = proxy.split(':');
      final host = parts[0];
      final port = parts.length > 1 ? parts[1] : '10808';

      // GNOME/Ubuntu 系统代理设置
      try {
        // 设置 SOCKS 代理
        await Process.run('gsettings', [
          'set',
          'org.gnome.system.proxy.socks',
          'host',
          host,
        ]);

        await Process.run('gsettings', [
          'set',
          'org.gnome.system.proxy.socks',
          'port',
          port,
        ]);

        // 设置代理模式为手动
        await Process.run('gsettings', [
          'set',
          'org.gnome.system.proxy',
          'mode',
          'manual',
        ]);

        print('✅ Linux (GNOME) 系统代理已设置: $proxy');
      } catch (e) {
        print('⚠️ GNOME 代理设置失败，可能不是 GNOME 桌面环境');
      }

      // KDE Plasma 系统代理设置
      try {
        final configFile = File('${Platform.environment['HOME']}/.config/kioslaverc');
        final content = '''
[Proxy Settings]
ProxyType=1
socksProxy=socks://$host:$port
''';
        await configFile.writeAsString(content);
        
        // 通知 KDE 代理设置已更改
        await Process.run('dbus-send', [
          '--type=signal',
          '/KIO/Scheduler',
          'org.kde.KIO.Scheduler.reparseSlaveConfiguration',
          'string:',
        ]);

        print('✅ Linux (KDE) 系统代理已设置: $proxy');
      } catch (e) {
        print('⚠️ KDE 代理设置失败，可能不是 KDE 桌面环境');
      }

      print('🌐 现在您可以直接在浏览器中访问 YouTube 等网站了！');
      print('💡 某些应用可能需要重启才能使用新的代理设置');
    } catch (e) {
      print('⚠️ 设置 Linux 代理失败: $e');
      print('💡 您可以手动在系统设置中配置 SOCKS 代理: $proxy');
      rethrow;
    }
  }
  
  /// 清除系统代理（跨平台）
  Future<void> _clearSystemProxy() async {
    try {
      if (Platform.isWindows) {
        await _clearWindowsProxy();
      } else if (Platform.isMacOS) {
        await _clearMacOSProxy();
      } else if (Platform.isLinux) {
        await _clearLinuxProxy();
      } else if (Platform.isAndroid || Platform.isIOS) {
        print('ℹ️ 移动平台代理已自动清除');
      }
    } catch (e) {
      print('⚠️ 清除系统代理失败: $e');
    }
  }

  /// 清除 Windows 系统代理
  Future<void> _clearWindowsProxy() async {
    try {
      // 禁用代理
      await Process.run('reg', [
        'add',
        'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
        '/v',
        'ProxyEnable',
        '/t',
        'REG_DWORD',
        '/d',
        '0',
        '/f',
      ]);
      
      print('✅ Windows 系统代理已清除');
    } catch (e) {
      print('⚠️ 清除 Windows 代理失败: $e');
      rethrow;
    }
  }

  /// 清除 macOS 系统代理
  Future<void> _clearMacOSProxy() async {
    try {
      // 获取所有网络服务
      final result = await Process.run('networksetup', ['-listallnetworkservices']);
      if (result.exitCode != 0) {
        throw Exception('无法获取网络服务列表');
      }

      final services = (result.stdout as String)
          .split('\n')
          .where((line) => line.isNotEmpty && !line.startsWith('*'))
          .toList();

      for (final service in services) {
        if (service.trim().isEmpty) continue;

        // 禁用 SOCKS 代理
        await Process.run('networksetup', [
          '-setsocksfirewallproxystate',
          service.trim(),
          'off',
        ]);

        print('✅ 已为 $service 清除 SOCKS 代理');
      }

      print('✅ macOS 系统代理已清除');
    } catch (e) {
      print('⚠️ 清除 macOS 代理失败: $e');
      rethrow;
    }
  }

  /// 清除 Linux 系统代理
  Future<void> _clearLinuxProxy() async {
    try {
      // GNOME/Ubuntu 系统代理清除
      try {
        // 设置代理模式为无
        await Process.run('gsettings', [
          'set',
          'org.gnome.system.proxy',
          'mode',
          'none',
        ]);

        print('✅ Linux (GNOME) 系统代理已清除');
      } catch (e) {
        print('⚠️ GNOME 代理清除失败');
      }

      // KDE Plasma 系统代理清除
      try {
        final configFile = File('${Platform.environment['HOME']}/.config/kioslaverc');
        if (await configFile.exists()) {
          final content = '''
[Proxy Settings]
ProxyType=0
''';
          await configFile.writeAsString(content);
          
          // 通知 KDE 代理设置已更改
          await Process.run('dbus-send', [
            '--type=signal',
            '/KIO/Scheduler',
            'org.kde.KIO.Scheduler.reparseSlaveConfiguration',
            'string:',
          ]);

          print('✅ Linux (KDE) 系统代理已清除');
        }
      } catch (e) {
        print('⚠️ KDE 代理清除失败');
      }

      print('💡 某些应用可能需要重启才能恢复正常网络设置');
    } catch (e) {
      print('⚠️ 清除 Linux 代理失败: $e');
      rethrow;
    }
  }
}
